import { SelectionModel } from '@angular/cdk/collections';
import { HttpClient, HttpResponse } from '@angular/common/http';
import { ThrowStmt } from '@angular/compiler';
import { Component, OnInit, SystemJsNgModuleLoader } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Data } from '@angular/router';
import { NzMessageService } from 'ng-zorro-antd/message';
import { forkJoin } from 'rxjs';
import { map, mergeMap, switchMap } from 'rxjs/operators';
import { SysroleService, UserSysrolePK } from 'sparrow-permission-lib';
import { Sysrole, Pageable } from 'sparrow-permission-lib';

@Component({
  selector: 'app-sysrole',
  templateUrl: './sysrole.component.html',
  styleUrls: ['./sysrole.component.css'],
})
export class SysroleComponent implements OnInit {
  listOfData: Sysrole[] = [];
  isVisible = false;
  pageable: Pageable = { page: 1, size: 20 };
  total: number = 0;

  validateForm!: FormGroup;

  constructor(
    private fb: FormBuilder,
    private apiService: SysroleService,
    private message: NzMessageService
  ) {}

  getSysroles(pageable: Pageable){
    this.apiService
    .all({
      page: this.pageable.page! - 1,
      size: this.pageable.size,
    })
    .subscribe((res) => {
      res.content?.forEach((f: any) => {
        this.apiService
          .getUsers(f.id, {
            page: 0,
            size: 100000,
          })
          .subscribe((users) => {
            f.users = users.content;
          });
      });
      console.log(res);

      this.listOfCurrentPageData = res.content!;
      this.total = res.totalElements!;
    });
  }

  ngOnInit(): void {
    this.getSysroles(this.pageable)
  }

  // pageable: Pageable = { page: 1, size: 10 }; // request page
  // page: Page = {}; // response page
  listOfCurrentPageData: readonly any[] = [];
  selectListSelection = new SelectionModel<any>(true);
  indeterminate = false; // use to control the all check style
  allChecked = false;

  onCurrentPageDataChange(listOfCurrentPageData: readonly Sysrole[]): void {
    this.listOfCurrentPageData = listOfCurrentPageData;
  }
  onPageIndexChange(page: number) {
    this.pageable.page = page;
    this.getSysroles(this.pageable)
    this.selectListSelection.clear();
  }

  onPageSizeChange(size: number) {
    this.pageable.size = size;
    this.getSysroles(this.pageable)
    this.selectListSelection.clear();
  }

  onItemChecked(sysrole: Sysrole, checked: boolean): void {
    this.selectListSelection.toggle(sysrole);

    if (
      this.selectListSelection.selected.length > 0 &&
      this.selectListSelection.selected.length <
        this.listOfCurrentPageData.length
    ) {
      this.indeterminate = true;
    } else {
      this.indeterminate = false;
    }
  }

  onAllChecked(checked: boolean): void {
    this.indeterminate = false;
    if (checked) {
      this.listOfCurrentPageData.forEach((sysrole) => {
        this.selectListSelection.select(sysrole);
      });
    } else {
      this.selectListSelection.clear();
    }
  }

  showNewModal(sysrole: any | null): void {
    if (sysrole === null) {
      this.validateForm = this.fb.group({
        name: [null, [Validators.required]],
        code: [null, [Validators.required]],
      });
    } else {
      this.validateForm = this.fb.group({
        name: [sysrole.name, [Validators.required]],
        code: [sysrole.code, [Validators.required]],
        id: [sysrole.id, [Validators.nullValidator]],
      });
    }

    this.isVisible = true;
  }

  handleCancel(): void {
    console.log('Button cancel clicked!');
    this.isVisible = false;
  }

  submitForm(): void {
    if (!this.validateForm.valid) {
      for (const i in this.validateForm.controls) {
        if (this.validateForm.controls.hasOwnProperty(i)) {
          this.validateForm.controls[i].markAsDirty();
          this.validateForm.controls[i].updateValueAndValidity();
        }
      }
    } else {
      let sysrole: any = this.validateForm.value;
      console.log(sysrole);
      if (sysrole.id === undefined) {
        this.apiService.create(sysrole, 'response').subscribe((res) => {
          if (res.status === 201) {
            this.isVisible = false;
            this.message.success('添加成功！' + sysrole.name);
            this.getSysroles(this.pageable)
          } else {
            this.message.error('添加失败，请检查角色代码是否重复！');
          }
        });
      } else {
        this.apiService.update1(sysrole.id!, sysrole).subscribe(
          (res) => {
            this.isVisible = false;
            this.message.success('更新成功成功！' + sysrole.name);
            this.onPageIndexChange(this.pageable.page!);
          },
          (error) => {
            this.message.error(error);
          }
        );
      }
    }
  }

  // permission

  validatePermissionForm!: FormGroup;
  isPermissionVisible: boolean = false;
  sysroleForPermission!: Sysrole | any;
  showPermissionModal(sysrole: Sysrole): void {
    if (sysrole !== null) {
      this.selectListSelection.clear();
      this.selectListSelection.select(sysrole);
    }
    this.validatePermissionForm = this.fb.group({
      name: [null, [Validators.required]],
    });
    this.isPermissionVisible = true;
    this.sysroleForPermission = sysrole;
  }

  handlePermissionCancel(): void {
    console.log('Button cancel clicked!');
    this.isPermissionVisible = false;
  }

  submitPermissionForm(): void {
    if (!this.validatePermissionForm.valid) {
      for (const i in this.validatePermissionForm.controls) {
        if (this.validatePermissionForm.controls.hasOwnProperty(i)) {
          this.validatePermissionForm.controls[i].markAsDirty();
          this.validatePermissionForm.controls[i].updateValueAndValidity();
        }
      }
    } else {
      this.apiService
        .addPermissions(
          this.sysroleForPermission.id,
          this.validatePermissionForm.value.name.split(',')
        )
        .subscribe((res) => {
          this.isPermissionVisible = false;
          this.getSysroles(this.pageable)
        });
    }
  }

  batchDelete() {
    this.apiService
      ._delete(
        this.selectListSelection.selected.map((sysrole: any) => sysrole.id)
      )
      .subscribe((res) => {
        this.message.success(
          '删除成功！' + this.selectListSelection.selected.length
        );
      });
  }

  delete(sysrole: any) {
    this.apiService
      ._delete([sysrole.id], 'response')
      .subscribe((res: HttpResponse<any>) => {
        if (res.status === 204) {
          this.message.success('删除成功！' + sysrole.name);
          this.getSysroles(this.pageable)
        } else {
          this.message.error('存在关联关系，请先删除关系后在删除。');
        }
      });
  }

  onUserRemove(id: UserSysrolePK, e: Event) {
    console.log(e);
    this.apiService
      .removePermissions(id.sysroleId!, [id.username!], 'response')
      .subscribe((res) => {
        if (res.status === 204) {
          this.message.success('取消授权成功！');
        } else {
          this.message.error('取消授权失败！');
        }
      });
  }
}
